﻿Imports System.Diagnostics.Eventing
Imports System.IO
Imports System.Management
Imports System.Net
Imports System.Net.Http
Imports System.Net.WebRequestMethods
Imports System.Security.Policy
Imports System.Xml
Imports HtmlAgilityPack
Imports Newtonsoft.Json
Imports NPOI.HSSF.UserModel
Imports NPOI.SS.UserModel
Imports OfficeOpenXml
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Text
Imports Org.BouncyCastle.Asn1.Pkcs
Imports System.Text

'Imports System.Text
Module Module1

    Sub Main()

        Console.WriteLine(Now.ToString("HH:mm"))

        'Dim a = "语文"， b = "不好学，特别是作文", c = a & b
        'Console.WriteLine(a)
        'Dim sasda = "adadadada"

        'Console.WriteLine(b)

        'Console.WriteLine(c)

        'Using reader As StreamReader = New StreamReader("C:\Users\Administrator\Desktop\新建文本文档 (1).json", Encoding.Default)
        '    Dim str = reader.ReadToEnd '.Replace("""""", """")

        '    Dim json = JsonConvert.DeserializeObject(Of Linq.JObject)(str)
        '    Dim l = json("data")("ret").Select(Function(x) New With {Key .WordName = x("word_name").ToString, .Word = x("word")}).ToList()
        '    Stop

        'End Using

        'Dim client As New WebClient With {.Encoding = Encoding.UTF8}
        'Dim str = client.DownloadString("https://tenapi.cn/v2/getip")
        'Dim d = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(str)
        'For Each kv In d("data")
        '    Console.WriteLine($"{kv.name}\t{kv.Value}")
        'Next
        'Dim ss = StrDup(20, "-")
        'Try
        '    Using sr As StreamReader = New StreamReader("C:\Users\Administrator\Desktop\新建文本文档.txt", Encoding.Default)
        '        Dim line As String
        '        line = sr.ReadLine()
        '        While line IsNot Nothing
        '            Console.WriteLine(line)
        '            line = sr.ReadLine()
        '        End While
        '    End Using
        'Catch ess As Exception
        '    Console.WriteLine("The file could not be read:")
        '    Console.WriteLine(ess.Message)
        'End Try

        'Console.ReadKey()

        'Dim brr = arr.OrderBy(Function(x) x(0)).ToArray
        Console.WriteLine("完成")

#Region "注释"

        ' Dim app As Excel.Application = GetObject(, "Excel.application")

        'Dim 头像 = TenApi.QQ头像获取("514439385")
        '头像.Save("C:\Users\Administrator\Desktop\头像.bmp")
        'client.
        'Dim a = client.GetAsync("http://localhost:5118/pizzas")
        'Task.WaitAll(a)
        'Dim response As HttpResponseMessage = a.Result
        'response.EnsureSuccessStatusCode()
        'Dim b = response.Content.ReadAsStringAsync
        'Task.WaitAll(b)
        'Dim responseBody = b.Result
        'Dim r = JsonConvert.DeserializeObject(responseBody)
        'For i = 0 To 2
        '    Console.WriteLine($"{r(i)("id")}{vbTab}{r(i)("name")}{vbTab}{r(i)("description")}")
        'Next
        'Dim uri As New Uri("http://localhost:5118/pizza")
        'Dim request As HttpWebRequest = WebRequest.Create(uri)
        'request.Method = "post"
        'Dim response1 As HttpWebResponse = request.GetResponse()
        'Using reader As New StreamReader(response1.GetResponseStream(), Encoding.UTF8)
        '    Dim rr = JsonConvert.DeserializeObject(reader.ReadToEnd)
        'End Using
        ' Win32.User32.1
        'Dim app As Excel.Application = GetObject(, "Excel.application")
        'Dim dt As DateTime = DateTime.FromOADate(app.Range("A1").Value2)
        'Console.WriteLine(dt)
        'Dim 一言随机输出一句话 = TenApi.一言随机输出一句话
        'Dim 随机二次元动漫图片 = TenApi.随机二次元动漫图片
        ' Dim 头像 = TenApi.QQ群头像获取("779595173")
        'Dim 号码 = {"13802384858", "15537053018", "15920936499", "13324090091", "15637576614", "18359692123", "19519544202", "15867035363", "18507698191", "15949751197", "15913172427", "18133018244"}
        'Dim uri As New Uri($"https://tenapi.cn/tel/?tel={号码(0)}")
        'Dim lines As New List(Of String)
        'Dim request As HttpWebRequest = WebRequest.Create(uri)
        'request.Method = "GET"
        ''request.Accept = "text/html,application/xhtml+xml,*/*"
        '' request.ContentType = "application/json"
        'Dim response As HttpWebResponse = request.GetResponse()
        'Using reader As New StreamReader(response.GetResponseStream(), Encoding.UTF8)
        '    Dim 解析结果 = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(reader.ReadToEnd)
        'End Using

#End Region

        Console.Read()
    End Sub

    Private Sub 图片批量加文字()
        Dim files = Directory.GetFiles("C:\Users\枸杞\Desktop\苍山街道照片", "*.jpg", SearchOption.AllDirectories)

        For Each f In files
            Dim text = IO.Path.GetFileNameWithoutExtension(f)
            Dim newImage As Image = New Bitmap(f)
            Dim g As Graphics = Graphics.FromImage(newImage)
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
            g.DrawImage(newImage, 0, 0)
            Dim fontSize As Single = 50
            Dim font As New Font("微软雅黑", fontSize)
            Dim fmt As StringFormat = StringFormat.GenericTypographic
            Dim brush As Brush = New SolidBrush(Color.Black)
            g.DrawString(text, font, brush, 20, 20)
            g.Dispose()
            newImage.Save("C:\Users\枸杞\Desktop\苍山街道照片 (1)\" & Directory.GetParent(f).Name & "\" & Path.GetFileName(f), ImageFormat.Jpeg)
            newImage.Dispose()
            Console.WriteLine(f)

        Next
    End Sub

    Function 手机号归属地查询(手机号 As String) As Dictionary(Of String, Object)
        Dim uri As New Uri($"https://tenapi.cn/tel/?tel={手机号}")
        Dim request As HttpWebRequest = WebRequest.Create(uri)

        Dim response As HttpWebResponse = request.GetResponse()
        Using reader As New StreamReader(response.GetResponseStream(), Encoding.UTF8)
            Return JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(reader.ReadToEnd)
        End Using
    End Function

    Private Sub NPOI读取文件()
        Dim path = "C:\Users\枸杞\Desktop\玄学问题.xls"
        Dim hssfworkbook As HSSFWorkbook
        Using file As New FileStream(path, FileMode.Open, FileAccess.Read)
            hssfworkbook = New HSSFWorkbook(file)
        End Using
        Dim sheet As ISheet = hssfworkbook.GetSheetAt(0)
        Dim rows = sheet.GetEnumerator
    End Sub

    Private Sub 多线程查询归属地()
        Dim sw As New Stopwatch
        sw.Start()
        Dim ts As New List(Of Task)
        Dim 号码 = {"13802384858", "15537053018", "15920936499", "13324090091", "15637576614", "18359692123", "19519544202", "15867035363", "18507698191", "15949751197", "15913172427", "18133018244"}
        For Each s In 号码
            ts.Add(Task.Run(Sub()
                                Dim Stopwatch As New Stopwatch
                                Stopwatch.Start()
                                Dim 归属地 = 查询归属地(s)
                                Console.WriteLine($"号码:{s}{vbTab}归属地:{归属地}     {vbTab}用时{Stopwatch.Elapsed}")
                            End Sub))
        Next
        Task.WaitAll(ts.ToArray)        '
        Console.WriteLine("全部完成,用时" & sw.Elapsed.ToString)
    End Sub

    Function 查询归属地(手机号 As String) As String
        Dim lines As New List(Of String)
        Dim uri As New Uri($"https://www.ip138.com/mobile.asp?mobile={手机号}&action=mobile")
        Dim web As New HtmlWeb With {.OverrideEncoding = System.Text.Encoding.UTF8}
        Dim doc = web.Load(uri)
        Dim note = doc.DocumentNode.SelectSingleNode("/html/body/div/div[2]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[2]/td[2]/span")
        Return note.InnerText
    End Function

    Private Sub eppluse插入行()
        ExcelPackage.LicenseContext = LicenseContext.NonCommercial
        Using p As New ExcelPackage("C:\Users\Administrator\Desktop\插入行测试.xlsx")
            With p.Workbook.Worksheets(0)
                .InsertRow(3, 1)
                .Cells(3, 1).LoadFromArrays({New Object() {1, 2, 3}})
            End With
            p.Save()
        End Using
    End Sub

    Private Sub 提取IP和MAC()
        Dim s As New Stopwatch
        s.Start()
        Dim Wmi As New System.Management.ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration")
        For Each WmiObj As ManagementObject In Wmi.Get
            If CBool(WmiObj("IPEnabled")) Then
                Console.WriteLine("IP(" & WmiObj("IPAddress")(0) & ")|MAC(" & WmiObj("MACAddress") & ")")
            End If
        Next
        Console.WriteLine(s.Elapsed)
    End Sub

    Public Function AddStringToImg(text As String) As String
        Dim phWidth As Integer = 470
        Dim basePath = Directory.GetCurrentDirectory()
        Console.WriteLine("获取根目录:" + basePath)
        Dim ts As TimeSpan = DateTime.Now - New DateTime(1970, 1, 1, 0, 0, 0,
        0)
        '用时间戳当做当前生成的文件名
        Dim timeStamp = Convert.ToInt64(ts.TotalSeconds).ToString()
        Dim savePath = String.Format("{0}/ShareImages/{1}.jpg", basePath, timeStamp)
        Console.WriteLine("保存图片名称地址:" + savePath)
        Dim tarFile = basePath + "/ShareImages/bg.jpg"
        '读取一个bmp图片
        Dim newImage As Image = New Bitmap(tarFile)
        '新建一个画板
        Dim g As Graphics = Graphics.FromImage(newImage)
        '设置质量
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
        '画图
        g.DrawImage(newImage, 0, 0)
        '#Region "自定义字体"
        '路径
        Dim strFontPath = basePath + "/simkai.ttf"
        '读取字体文件
        Dim pfc As New PrivateFontCollection()
        pfc.AddFontFile(strFontPath)
        '实例化字体
        Dim fontSize As Single = 20
        Dim font As New Font(pfc.Families(0), fontSize)
        '#End Region

        ' 自定义行间距
        Dim fit As New SizeF(phWidth, font.Height + 5)
        Dim fmt As StringFormat = StringFormat.GenericTypographic
        Dim spacing As Integer = CInt(font.Height)
        '自定义字体颜色
        Dim brush As Brush = New SolidBrush(Color.FromArgb(65, 65, 65))
        Dim line As Integer = 5
        '限制内容长度，超过的文字用...代替
        If text.Length > 140 Then
            text = text.Substring(0, 140) + "..."
        End If
        Dim ix As Integer = 0
        While ix < text.Length
            Dim chars As Integer, lines As Integer
            g.MeasureString(text.Substring(ix), font, fit, fmt, chars, lines)
            g.DrawString(text.Substring(ix, chars), font, brush, 10, spacing * line)
            line += 1
            ix += chars
        End While
        '保存图
        newImage.Save(savePath, ImageFormat.Jpeg)
        '释放资源
        g.Dispose()
        newImage.Dispose()
        Return timeStamp
    End Function

End Module